package com.liyujie.serialport.receiver;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.SerialInputOutputManager;
import com.liyujie.serialport.mobile.SKData;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import in.xiandan.countdowntimer.CountDownTimerSupport;
import in.xiandan.countdowntimer.OnCountDownTimerListener;

/**
 * CH340转串口（刷卡）
 */
public class CH340USBSK extends Service {
    private String INTENT_ACTION_GRANT_USB = "com.hoho.android.usbserial.examples.GRANT_USB";

    public static UsbManager manager;
    private List<UsbSerialDriver> availableDrivers;
    private SerialInputOutputManager mSerialIoManager;
    private UsbSerialPort usbSerialPort;
    private LocalBinder binder = new LocalBinder();
    /**
     * 反射
     */
    public static UsbSerialDriver usbSerialDriver;
    /**
     * 授权成功
     */
    public static boolean authorizationSucceed = false;


    //倒计时
    private StringBuffer buffer = new StringBuffer();
    private CountDownTimerSupport countDownTimerSupport = new CountDownTimerSupport(500, 100);
    /**
     * 创建Binder对象，返回给客户端即Activity使用，提供数据交换的接口
     */
    public class LocalBinder extends Binder {
        // 声明一个方法，getService。（提供给客户端调用）
        public CH340USBSK getService() {
            // 返回当前对象LocalService,这样我们就可在客户端端调用Service的公共方法了
            return CH340USBSK.this;
        }
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        manager = (UsbManager)getSystemService(Context.USB_SERVICE);
        availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
        if (availableDrivers.isEmpty()) {
            return;
        }
        UsbSerialDriver driver;
        if(availableDrivers.size() > 0){
            driver = availableDrivers.get(0);
        }else {
            ToastUtils.make().show("CH340开启失败");
            return;
        }
        UsbDeviceConnection connection = manager.openDevice(usbSerialDriver.getDevice());
        if (connection == null) {
            PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(INTENT_ACTION_GRANT_USB), 0);
            manager.requestPermission(driver.getDevice(), usbPermissionIntent);
            ToastUtils.make().show("请勾选USB权限，重新启动应用");
            // You probably need to call UsbManager.requestPermission(driver.getDevice(), ..)
            return;
        }
        // Read some data! Most have just one port (port 0).
        usbSerialPort = usbSerialDriver.getPorts().get(0);
        try {
            usbSerialPort.open(connection);
            usbSerialPort.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
            mSerialIoManager = new SerialInputOutputManager(usbSerialPort, mListener);//添加监听
            mSerialIoManager.setReadTimeout(100);
            mSerialIoManager.start();
            ToastUtils.make().show("CH340开启成功");
            /**
             * 授权成功
             */
            authorizationSucceed = true;
        } catch (Exception exception) {
            // Deal with error.
            LogUtils.d(exception.getMessage());
        }
        //倒计时
        countDownTimerSupport.setOnCountDownTimerListener(new OnCountDownTimerListener() {
            @Override
            public void onTick(long millisUntilFinished) {

            }
            @Override
            public void onFinish() {
                EventBus.getDefault().post(new SKData(buffer.toString()));
                buffer = new StringBuffer();
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private SerialInputOutputManager.Listener mListener = new SerialInputOutputManager.Listener() {
        @Override
        public void onRunError(Exception e) {
        }

        @Override
        public void onNewData(final byte[] data) {
            String swipingCard = ConvertUtils.bytes2HexString(data);
            if(countDownTimerSupport.isStart()){
                if(buffer.length() > 0){
                    buffer.append(swipingCard);
                }
            }else {
                buffer.append(swipingCard);
                countDownTimerSupport.reset();
                countDownTimerSupport.start();
            }

        }
    };

}
